package controllers

import (
	"bestcore/base"
	"bestcore/common/jwt"
	"bestcore/common/response"
	"time"

	"github.com/gofiber/fiber/v2"
)

func init() {
	Controllers = append(Controllers, new(JwtController))
}

type JwtController struct{ base.BaseController }

func (controller *JwtController) Install(app *fiber.App) {

	app.Post("/login", controller.Login)
	app.Post("/login/check", jwt.GetMiddleware(), controller.LoginCheck)
}

func (controller *JwtController) Login(c *fiber.Ctx) error {
	username := c.FormValue("username")
	password := c.FormValue("password")

	if username != "bestlyg" || password != "123456" {
		return response.Fail(c, "帐号密码错误")
	}

	token, err := jwt.GetToken(map[string]interface{}{
		"name":  username,
		"admin": true,
		"exp":   time.Now().Add(time.Hour * 72).Unix(),
	})

	if err != nil {
		return response.Fail(c, err.Error())
	}

	return response.Success(c, fiber.Map{"token": token})
}
func (controller *JwtController) LoginCheck(c *fiber.Ctx) error {
	claims := jwt.GetClaims(c)
	return response.Success(c, "Welcome "+claims["name"].(string))
}
